

public class BinaryTreeBuilder {
   public static class TreeNode {
        char val;
        TreeNode left;
        TreeNode right;

        TreeNode(char x) {
            val = x;
        }
    }

    // 构建二叉树
    public static TreeNode buildTree(String preorder) {
        return buildTree(preorder, 0);
    }

    private static TreeNode buildTree(String preorder, int index) {
        if (index >= preorder.length() || preorder.charAt(index) == '#') {
            return null;
        }

        // 创建当前节点
        TreeNode node = new TreeNode(preorder.charAt(index));

        // 递归构建左子树和右子树
        // 假设每个节点后面紧跟着的是左子树，然后是右子树
        int leftTreeSize = 0;
        for (int i = index + 1; i < preorder.length(); i++) {
            if (preorder.charAt(i) == '#') {
                leftTreeSize++;
            } else {
                break;
            }
        }

        // 左子树的大小加1是因为当前索引指向根节点
        node.left = buildTree(preorder, index + 1 + leftTreeSize);
        node.right = buildTree(preorder, index + 1 + leftTreeSize + 1);

        return node;
    }

    public static void main(String[] args) {
        String preorder = "ABDG##HI####CE#J##F##";
        TreeNode root = buildTree(preorder);
        // 这里可以添加代码来遍历或操作构建的二叉树
    }
}